package ru.artyushov.fingers.core.basic;

import ru.artyushov.fingers.core.BinarizationStrategy;
import ru.artyushov.fingers.core.data.Fingerprint;

import java.awt.*;
import java.awt.image.BufferedImage;

public class LightnessBasedBinarizer implements BinarizationStrategy {
    @Override
    public Fingerprint toFingerprint(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        
        boolean[][] data = new boolean[width][height];
        double[][] lightnessMap = new double[width][height];

        double totalLightness = 0.0;
        
        final float[] hsv = new float[3]; // initialized just once for performance reasons

        for(int col = 0; col < width; col ++) {
            for(int row = 0; row < height; row ++) {
                int color = image.getRGB(col, row);

                // note the heading zeroes, they are used to filter out alpha chanel data
                int  red = (color & 0x00ff0000) >> 16;
                int  green = (color & 0x0000ff00) >> 8;
                int  blue = color & 0x000000ff;
                
                Color.RGBtoHSB(red, green, blue, hsv);

                double lightness = hsv[2];

                totalLightness += lightness;

                lightnessMap[col][row] = lightness;
            }
        }

        double averageLightness = totalLightness / (width * height);

        for(int col = 0; col < width; col ++) {
            for(int row = 0; row < height; row ++) {
                data[col][row] = lightnessMap[col][row] < averageLightness;
            }
        }
        
        return new Fingerprint(data, height);
    }
}
